package com.jsam.controller.user;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.jsam.dtos.UserDto;
import com.jsam.service.UserService;

public class RegisterController extends SimpleFormController {
	private UserService userService;
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {		
		ModelAndView mv=new ModelAndView();

		UserDto dto=(UserDto)command;
		dto.setPassword(RSHash(dto.getPassword()).trim());				
		
		userService.addUser(dto);					
		request.getSession().setAttribute("login",dto);
		
		
		mv.setViewName(getSuccessView());				
		return mv;
	}	
	
	
	public String RSHash(String password) {
	      int b     = 378551;
	      int a     = 63689;
	      long hash = 0;

	      for(int i = 0; i < password.length(); i++) {
	         hash = hash * a + password.charAt(i);
	         a    = a * b;
	      }

	      return String.valueOf(hash);
	}

}
